package http;

import java.io.IOException;

public class PackedPartedDownload extends SubjectImpl implements IObserver {
	private PartedDownload download;
	private String rarExtractor;
	public void setRarExtractor(String rarExtractor) {
		this.rarExtractor = rarExtractor;
	}
	private String targetDirectory;
	private String password;
	public void addDownload(String name,String link) {
		System.out.println("PackedPartedDownload::addDownload("+name+","+link+")");
		download.addDownload(name,link);
	}
	public void setCookies(String cookies) {
		download.setCookies(cookies);
	}
	public void setTargetDirectory(String targetDirectory) {
		this.targetDirectory = targetDirectory;
		download.setTargetDirectory(targetDirectory);
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public PackedPartedDownload() {
		download = new PartedDownload();
	}
	@Override
	public void run() {
		download.addObserver(this);
		download.start();
		System.out.println("PackedPartedDownload::run download.start()");
	}
	public void runUnpackCommand() {
		System.out.println("Starting unpack of File: "+
				download.getDoneDownloads()
				.get(0).getTargetFile().getAbsolutePath()+ " to "+
				targetDirectory);
		String[] s = {
				rarExtractor,
				"e",
				"-p".concat(password),
				"-o+",
				"\""+download.getDoneDownloads()
					.get(0).getTargetFile().getAbsolutePath()+"\"",
				"\""+targetDirectory+"\""
			};
		Process p;
		try {
			p = Runtime.getRuntime().exec(s);
			try {
				if (p.waitFor() == 0) {
					System.out.println("... done! Deleting Files:");
					for (Download singleDownload:download.getDoneDownloads()) {
						System.out.println("File "+singleDownload.getTargetFile().getAbsolutePath()+" ...");
						singleDownload.getTargetFile().delete();
						System.out.println("... deleted!");
					}
				}
				else {
					System.out.println("Could not run the command:");
					for (String param:s)
						System.out.print(param+" ");
					System.out.println();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
	@Override
	public void update(ISubject o) {
		System.out.println("PackedPartedDownload::update() DownloadState of PartedDownload: "+o.getSubjectState());
		if (o.getSubjectState() == 100) {
			runUnpackCommand();
		}
	}
}
